#!/usr/bin/env python
"""
        qsiauth.myuser
==================================
        :user level decorator
"""
from qsiauth.constants import *

def user_level(data):
    if data['access_level'] == USER_ACCESS_LEVEL:
        access = True
    if data['access_level'] == ADMIN_ACCESS_LEVEL:
        access = True
    if data['access_level'] == MANAGER_ACCESS_LEVEL:
        access = True
    return access
def g_user_level(data):
    if data['access_level'] == GROUP_ACCESS_LEVEL:
        access = True
    if data['access_level'] == GROUP_MANAGE_LEVEL:
        access = True
    if data['access_level'] == ADMIN_ACCESS_LEVEL:
        access = True
    return access
def group_level(data):
    if data['access_level'] == GROUP_MANAGE_LEVEL:
        access = True
    if data['access_level'] == ADMIN_ACCESS_LEVEL:
        access = True
    return access
def manager_level(data):
    if data['access_level'] == ADMIN_ACCESS_LEVEL:
        access = True
    if data['access_level'] == MANAGER_ACCESS_LEVEL:
        access = True
    return access
def admin_level(data):
    return data['access_level'] == ADMIN_ACCESS_LEVEL
def logout(self):
    self.redirect(self.uri_for('pages-root'), abort=True)


def myauthorise(role):
    """
        Decorator that checks if there's a user associated with the current session.
        Will also fail if there's no session present.
    """
    def user_required(handler):
          def check_login(self, *args, **kwargs):
                user = self.user_info
                if user is None:
                    self.redirect(self.uri_for('pages-root'), abort=True)
                else:
                    data = user.to_dict()
                    if data is None or data['access_level'] == USER_NOT_APPROVED:
                        logout(self)
                    else:
                        if role == 'user' and not user_level(data):
                            logout(self)
                        if role == 'groupManager' and not group_level(data):
                            logout(self)
                        if role == 'manager' and not manager_level(data):
                            logout(self)
                        if role == 'admin' and not admin_level(data):
                            logout(self)
                        pass
                    return handler(self, *args, **kwargs)
          return check_login
    return user_required